﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Diagnostics;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;

using FCNS.KeepMoney.Configuration;
using FCNS.KeepMoney.Util;

namespace FCNS.KeepMoney.Data
{
    #region GtdGroupField
    public class GtdGroupField
    {
        public void Remove()
        {
            foreach (DataRow row in KMData.DataTableGtdEntrys.Select("GtdGroupId = " + Id))
                KMData.DataTableGtdEntrys.Rows.Remove(row);

            KMData.DataTableGtdGroups.Rows.Remove(dRow);
            fields.Remove(this);
        }

        static List<GtdGroupField> fields = new List<GtdGroupField>();
        public static List<GtdGroupField> GetGtdGroupField
        {
            get
            {
                if (fields.Count == 0)
                    foreach (DataRow row in KMData.DataTableGtdGroups.Rows)
                        fields.Add(new GtdGroupField(row));

                return fields;
            }
        }

        bool add = false;
        public void AddRowToDataTable()
        {
            if (!add)
                return;

            KMData.DataTableGtdGroups.Rows.Add(dRow);
            fields.Add(this);
            add = false;
        }


        DataRow dRow = null;
        public GtdGroupField(DataRow row)
        {
            dRow = row;
            GetColor(Color);
        }

        public GtdGroupField(GtdColor color)
        {
            dRow = KMData.DataTableGtdGroups.NewRow();
            add = true;
            Color = color;
        }

        public int Id
        {
            get { return (int)dRow["Id"]; }
            set { dRow["Id"] = value; }
        }

        public string Name
        {
            get { return (string)dRow["Name"]; }
            set { dRow["Name"] = value; }
        }

        public bool Checked
        {
            get { return (bool)dRow["Checked"]; }
            set { dRow["Checked"] = value; }
        }

        public GtdColor Color
        {
            get { return (GtdColor)dRow["Color"]; }
            set { dRow["Color"] = (int)value; }
        }

        private void GetColor(GtdColor color)
        {
            switch (color)
            {
                case GtdColor.蓝色:
                    colorBorder = System.Drawing.Color.FromArgb(255, 0, 81, 212);
                    colorText = System.Drawing.Color.FromArgb(255, 255, 255, 255);
                    colorBgUnselected = System.Drawing.Color.FromArgb(200, 141, 181, 242);
                    colorBgSelectedLeft = System.Drawing.Color.FromArgb(255, 28, 104, 224);
                    colorBgSelectedRight = System.Drawing.Color.FromArgb(255, 90, 149, 245);
                    break;
                case GtdColor.橙色:
                    colorBorder = System.Drawing.Color.FromArgb(255, 245, 118, 0);
                    colorText = System.Drawing.Color.FromArgb(255, 255, 255, 255);
                    colorBgUnselected = System.Drawing.Color.FromArgb(200, 245, 211, 180);
                    colorBgSelectedLeft = System.Drawing.Color.FromArgb(255, 247, 129, 17);
                    colorBgSelectedRight = System.Drawing.Color.FromArgb(255, 255, 164, 79);
                    break;
                case GtdColor.蔷薇色:
                    colorBorder = System.Drawing.Color.FromArgb(255, 176, 39, 174);
                    colorText = System.Drawing.Color.FromArgb(255, 255, 255, 255);
                    colorBgUnselected = System.Drawing.Color.FromArgb(200, 232, 171, 232);
                    colorBgSelectedLeft = System.Drawing.Color.FromArgb(255, 186, 67, 184);
                    colorBgSelectedRight = System.Drawing.Color.FromArgb(255, 196, 90, 196);
                    break;
                case GtdColor.珊瑚红:
                    colorBorder = System.Drawing.Color.FromArgb(255, 230, 23, 23);
                    colorText = System.Drawing.Color.FromArgb(255, 255, 255, 255);
                    colorBgUnselected = System.Drawing.Color.FromArgb(200, 251, 171, 171);
                    colorBgSelectedLeft = System.Drawing.Color.FromArgb(255, 244, 44, 44);
                    colorBgSelectedRight = System.Drawing.Color.FromArgb(255, 250, 97, 97);
                    break;
                case GtdColor.紫罗兰:
                    colorBorder = System.Drawing.Color.FromArgb(255, 73, 43, 161);
                    colorText = System.Drawing.Color.FromArgb(255, 255, 255, 255);
                    colorBgUnselected = System.Drawing.Color.FromArgb(200, 195, 183, 233);
                    colorBgSelectedLeft = System.Drawing.Color.FromArgb(255, 92, 64, 176);
                    colorBgSelectedRight = System.Drawing.Color.FromArgb(255, 171, 149, 237);
                    break;
                default:
                    colorBorder = System.Drawing.Color.FromArgb(255, 44, 161, 11);
                    colorText = System.Drawing.Color.FromArgb(255, 255, 255, 255);
                    colorBgUnselected = System.Drawing.Color.FromArgb(200, 158, 241, 136);
                    colorBgSelectedLeft = System.Drawing.Color.FromArgb(255, 68, 173, 38);
                    colorBgSelectedRight = System.Drawing.Color.FromArgb(255, 113, 194, 91);
                    break;
            }
        }

        Color colorBorder, colorText, colorBgUnselected, colorBgSelectedLeft, colorBgSelectedRight;
        /// <summary>
        /// 获取日历任务栏目的填充颜色
        /// </summary>
        public Color ColorBorder
        {
            get
            {
                return colorBorder;
            }
        }
        /// <summary>
        /// 获取日历任务栏目的文本颜色
        /// </summary>
        public Color ColorText
        {
            get
            {
                return colorText;
            }
        }
        /// <summary>
        /// 获取日历任务栏目未选择状态的背景颜色
        /// </summary>
        public Color ColorBgUnselected
        {
            get
            {
                return colorBgUnselected;
            }
        }
        /// <summary>
        /// 获取日历任务栏目选择状态的左背景颜色
        /// </summary>
        public Color ColorBgSelectedLeft
        {
            get
            {
                return colorBgSelectedLeft;
            }
        }
        /// <summary>
        /// 获取日历任务栏目选择状态的右背景颜色
        /// </summary>
        public Color ColorBgSelectedRight
        {
            get
            {
                return colorBgSelectedRight;
            }
        }
    }

    #endregion

    #region GtdEntryField
    public class GtdEntryField
    {
        public void Remove()
        {
            KMData.DataTableGtdEntrys.Rows.Remove(dRow);
        }

        public static List<GtdEntryField> GetGtdEntryField(DateTime? startTime, DateTime? endTime, bool ShowOverdueData)
        {
            List<GtdEntryField> fields = new List<GtdEntryField>();

            StringBuilder sb = new StringBuilder();
            if (startTime != null)
            {
                sb.Append("StartDateTime >= '" + startTime + "'");
                if (endTime != null)
                    sb.Append(" and EndDateTime <= '" + endTime + "'");
            }
            else if (endTime != null)
                sb.Append("EndDateTime <= '" + endTime + "'");

            if (!ShowOverdueData)
            {
                if (sb.Length > 0)
                    sb.Append(" and ");

                sb.Append("Finish = false");
            }

            foreach (DataRow row in KMData.DataTableGtdEntrys.Select(sb.ToString()))
                fields.Add(new GtdEntryField(row));

            return fields;
        }

        bool add = false;
        public void AddRowToDataTable()
        {
            if (!add)
                return;

            KMData.DataTableGtdEntrys.Rows.Add(dRow);
            add = false;
        }

        DataRow dRow = null;
        public GtdEntryField(DataRow row)
        {
            Debug.Assert(row != null);
            dRow = row;
        }

        public GtdEntryField(int GtdGroupId)
        {
            dRow = KMData.DataTableGtdEntrys.NewRow();
            dRow["GtdGroupId"] = GtdGroupId;
            add = true;
        }

        public DateTime StartTime
        {
            get { return (DateTime)dRow["StartDateTime"]; }
            set { dRow["StartDateTime"] = value; }
        }

        public DateTime EndTime
        {
            get { return (DateTime)dRow["EndDateTime"]; }
            set { dRow["EndDateTime"] = value; }
        }

        public bool Finish
        {
            get
            {
                return (bool)dRow["Finish"];
            }
            set
            {
                dRow["Finish"] = value;
            }
        }

        public string Title
        {
            get
            {
                return (string)dRow["Name"];
            }
            set
            {
                dRow["Name"] = value;
            }
        }

        public string Note
        {
            get
            {
                return (string)dRow["Note"];
            }
            set
            {
                dRow["Note"] = value;
            }
        }

        public int Level
        {
            get { return (int)dRow["Level"]; }
            set { dRow["Level"] = value; }
        }

        public GtdGroupField GtdGroup
        {
            get { return new GtdGroupField(KMData.DataTableGtdGroups.Select("Id = " + dRow["GtdGroupId"])[0]); }
            set { dRow["GtdGroupId"] = value.Id ; }
        }
    }
    #endregion

    #region InterestField
    public class InterestField
    {
        static Dictionary<string, int> dic = new Dictionary<string, int>();
        public static Dictionary<string, int> InterestMode
        {
            get
            {
                if (dic.Count == 0)
                {
                    //不能更改此次序
                    dic[LanguageUtil.日息] = 0;
                    dic[LanguageUtil.周息] = 1;
                    dic[LanguageUtil.月息] = 2;
                    dic[LanguageUtil.年息] = 3;
                }

                return dic;
            }
        }


        public void Remove()
        {
            KMData.DataTableInterest.Rows.Remove(dRow);
            fields.Remove(this);
        }

        bool add = false;
        public void AddRowToDataTable()
        {
            if (!add)
                return;

            KMData.DataTableInterest.Rows.Add(dRow);
            fields.Add(this);
            add = false;
        }

       static  List<InterestField> fields = new List<InterestField>();
        public static List<InterestField> GetInterestField
        {
            get
            {
                if (fields.Count == 0)
                    foreach (DataRow row in KMData.DataTableInterest.Rows)
                        fields.Add(new InterestField(row));

                return fields;
            }
        }

        DataRow dRow = null;
        public InterestField(DataRow row)
        {
            if (row == null)
            {
                dRow = KMData.DataTableInterest.NewRow();
                add = true;
            }
            else
                dRow = row;
        }

        public int Id
        {
            get { return (int)dRow["Id"]; }
            set { dRow["Id"] = value; }
        }

        public int Mode
        {
            get { return (int)dRow["Mode"]; }
            set { dRow["Mode"] = value; }
        }

        public decimal Value
        {
            get { return (decimal)dRow["Value"]; }
            set { dRow["Value"] = value; }
        }

        public string columnName
        {
            get { return (string)dRow["Name"]; }
            set { dRow["Name"] = value; }
        }

        public string columnMode
        {
            get
            {
                foreach (KeyValuePair<string, int> k in dic)
                {
                    if (k.Value == Mode)
                        return k.Key;
                }

                Debug.Assert(false, "FCNS.KeepMoney.Data.InterestField.columnMode");

                return string.Empty;
            }
        }

        public string columnValue
        {
            get
            {
                if (Value > 1)
                    return Value.ToString();
                else
                    return Value.ToString("p"+Program.AppConfig.Money.Precision.ToString());
            }
        }

    }
    #endregion

    #region TagField
    public class TagField
    {
        TagField() { }

        public static void RemoveTag(string tag)
        {
            DataRow r = KMData.DataTableTags.Select("Name = '" + tag + "'")[0];
            if ((int)r["Amout"] > 1)
                r["Amout"] = (int)r["Amout"] - 1;
            else
            {
                if (tag == LanguageUtil.借款 || tag == LanguageUtil.贷款)
                    r["Amout"] = 0;
                else
                {
                    KMData.DataTableTags.Rows.Remove(r);
                    tags.Remove(tag);
                }
            }
        }

        static List<string> tags = new List<string>();
        public static List<string> GetTagField
        {
            get
            {
                if (tags.Count == 0)
                    foreach (DataRow r in KMData.DataTableTags.Rows)
                        tags.Add((string)r["Name"]);

                return tags;
            }
        }

        public static void NewTag(string tag)
        {
            DataRow r = KMData.DataTableTags.NewRow();
            r["Name"] = tag;
            KMData.DataTableTags.Rows.Add(r);
            tags.Add(tag);
        }

        public static void AddTag(List<string> tags)
        {
            foreach (string tag in tags)
            {
                DataRow r = KMData.DataTableTags.Select("Name = '" + tag + "'")[0];
                r["Amout"] = (int)r["Amout"] + 1;
            }
        }
    }
    #endregion

    #region AccountField
    public class AccoutField
    {
        public static AccoutField GetAccountFieldByTag(string tag)
        {
            return new AccoutField(KMData.DataTableAccounts.Select("Tag = '" + tag + "'")[0]);
        }

        DataRow dRow = null;
        public AccoutField(DataRow row)
        {
            dRow = row;
        }

        public string Name
        {
            get { return (string)dRow["Name"]; }
            set
            {
                dRow["Name"] = value;
            }
        }

        public string Password
        {
            get { return (string)dRow["Password"]; }
            set
            {
                dRow["Password"] = value;
            }
        }
    }
    #endregion

    #region EntryField
    public class EntryField
    {
        public void Remove()
        {
            BankField.GetBankField.Find(bf => { return bf.Id == BankId; }).SetBankBalance(-Money);
            KMData.DataTableEntrys.Rows.Remove(dRow);
            fields.Remove(this);
        }

        static AceMoney configUI = Program.AppConfig.Money;
        static AceApplication configApp = Program.AppConfig.App;

        static List<EntryField> fields=new List<EntryField>();
        public static List<EntryField> GetEntryField
        {
            get
            {
                if (fields.Count == 0)
                {
                    ////DateTime start = DateTimeUtil.yyyyMMdd(Program.YearShown.Year, 1, 1);
                    //DateTime end = DateTimeUtil.yyyyMMdd(Program.YearShown.Year, 12, 31);
                    foreach (DataRow row in KMData.DataTableEntrys.Rows)
                        fields.Add(new EntryField(row));
                }
                return fields;
            }
        }

        bool add = false;
        /// <summary>
        /// 将 EntryField 实例写入数据库
        /// </summary>
        public void AddRowToDataTable()
        {
            if (!add)
                return;

            Debug.Assert(BankField.GetBankField.Find(gbf => { return gbf.Id == this.BankId; }).Enable, "AddEntryField");

            KMData.DataTableEntrys.Rows.Add(dRow);
            fields.Add(this);
            add = false;

            BankField.GetBankField.Find(bf => { 
                return bf.Id == BankId; }).SetBankBalance(Money);
        }

        DataRow dRow = null;
        public DataRow Row
        {
            get { return dRow; }
        }
        
        public EntryField(DataRow row)
        {
            Debug.Assert(row != null, "KMDataField.EntryField(DataRow row)");

            dRow = row;
            if (Money > 0)
                flag = "+";
            else
                flag="-";

            if ((!configUI.ShowPlus && flag == "+") || (!configUI.ShowMinus && flag == "-"))
                flag = string.Empty;
        }

        public EntryField(int groupId, int bankId,  DateTime date, decimal money, KMDEntryType entryType)
        {
            if (money == 0)
                return;

            if(!GroupField.GetGroupType(groupId))
                if (!BankField.VerifyWhetherSufficientToPay(bankId, money))
                    return;

            dRow = KMData.DataTableEntrys.NewRow();
           // columnName= name;
            GroupId = groupId;
            BankId = bankId;
           // columnNote= note;
            Date = date;
            Money= money;
            EntryType =entryType;
           // Mark= mark;

            add = true;
        }

        public EntryField(int groupId)
        {
            dRow = KMData.DataTableEntrys.NewRow();
            add = true;
            GroupId = groupId;
        }
        
        public string Mark
        {
            get { return (string)dRow["Mark"]; }
            set { dRow["Mark"] = value; }
        }

        public KMDEntryType EntryType
        {
            get { return (KMDEntryType)((int)dRow["EntryType"]); }
            set { dRow["EntryType"] = (int)value; }
        }

        public int Id
        {
            get { return (int)dRow["Id"]; ; }
        }

        public int GroupId
        {
            get {
                return (int)dRow["GroupId"]; }
            set
            {
                dRow["GroupId"] = value;
            }
        }

        public int BankId
        {
            get {return (int)dRow["BankId"];            }
            set
            {
                dRow["BankId"] = value;
            }
        }

        public string columnName
        {
            get { return (string)dRow["Name"]; }
            set
            {
                dRow["Name"] = value;
            }
        }

        public DateTime Date
        {
            get { return (DateTime)dRow["Date"]; }
            set
            {
                dRow["Date"] = value;
            }
        }
        public string columnDate
        {
            get { return Date.ToString(configApp.DateFormat); }
        }

        string flag = string.Empty;
        public string columnMoney
        {
            get { return flag + string.Format("{0:f" + Program.AppConfig.Money.DecimalPlaces + "}", Math.Abs(Money)); }
        }
        public decimal Money
        {
            get { return (decimal)dRow["Money"]; }
            set
            {
                decimal de = value;
                if (GroupField.GetGroupType(GroupId) && value < 0)
                    de = -de;
                else if (!GroupField.GetGroupType(GroupId) && value > 0)
                    de = -de;

                dRow["Money"] =de;
            }
        }

        public string columnNote
        {
            get { return (string)dRow["Note"]; }
            set
            {
                dRow["Note"] = value;
            }
        }

        public string columnAlertDate
        {
            get
            {
                if (AlertDate != null)
                    return ((DateTime)AlertDate).ToString(configApp.DateFormat);
                else
                    return string.Empty;
            }
        }
        public DateTime? AlertDate
        {
            get
            {
                if (dRow["AlertDate"] is DBNull)
                    return null;
                else
                    return (DateTime)dRow["AlertDate"];
            }
            set
            {
                if (value !=null)
                    dRow["AlertDate"] = value;
                else
                    dRow["AlertDate"] = DBNull.Value;
            }
        }

        public string columnTag
        {
            get
            {
                if (dRow["Tag"] is DBNull)
                    return string.Empty;
                else
                    return (string)dRow["Tag"];
            }
            set { dRow["Tag"] = value; }
        }

        public string columnBankName
        {
            get
            {
                try { return BankField.GetBankField.Find(bf => { return bf.Id == BankId; }).Name; }
                catch
                {
                    Debug.Assert(false, "column_BankName");
                    return string.Empty;
                }
            }
        }

        public string columnGroupName
        {
            get
            {
                try
                {
                    return GroupField.GetGroupField.Find(gf => { return gf.Id == GroupId; }).Name;
                }
                catch
                {
                    Debug.Assert(false, "column_GroupName");
                    return string.Empty;
                }
            }
        }

        //public bool Income
        //{
        //    get { return GroupField.GetGroupType(GroupId); }
        //}
    }
    #endregion

    #region RegularEntryField
    public class RegularEntryField
    {
        decimal moneyPerTime=0;
        public decimal MoneyPerTime
        {
            get
            {
                if (moneyPerTime == 0)
                    CalcMoneyPerTime();

                return moneyPerTime;
            }
        }

        private void CalcMoneyPerTime()
        {
        }
            

        static List<RegularEntryField> fields = new List<RegularEntryField>();
        public static List<RegularEntryField> GetRegularEntryField
        {
            get
            {
                if (fields.Count == 0)
                    foreach (DataRow row in KMData.DataTableRegular.Rows)
                    {
                        RegularEntryField r = new RegularEntryField(row);
                        fields.Add(r);
                    }
                return fields;
            }
        }

        public void Remove()
        {
            foreach (EntryField ef in EntryField.GetEntryField.FindAll(ef => { return ef.Mark == Id.ToString(); }))
                ef.Remove();

            KMData.DataTableRegular.Rows.Remove(dRow);
            fields.Remove(this);
        }

        bool add = false;
        public void AddRowToDataTable()
        {
            if (!add)
                return;

            KMData.DataTableRegular.Rows.Add(dRow);
            fields.Add(this);
            add = false;
        }

        DataRow dRow = null;
        public RegularEntryField(DataRow row)
        {
            if (row == null)
            {
                dRow = KMData.DataTableRegular.NewRow();
                add = true;
            }
            else
                dRow = row;
        }


        public int Id
        {
            get { return (int)dRow["Id"]; }
        }

        public string columnNote
        {
            get { return (string)dRow["Note"]; }
            //set { dRow["Note"] = value; }
        }
        /// <summary>
        /// 已完成期数
        /// </summary>
        public int Finish
        {
            get { return (int)dRow["Finish"]; }
            set { dRow["Finish"] = value; }
        }

        public string columnFinish2
        {
            get { return dRow["Finish"].ToString() + "/" + dRow["Time"].ToString(); }
        }

        public int GroupId
        {
            get { return (int)dRow["GroupId"]; }
            set { dRow["GroupId"] = value; }
        }

        public string columnGroupName
        {
            get { return KMData.GetGroupNameById((int)dRow["GroupId"]); }
        }

        public int BankId
        {
            get { return (int)dRow["BankId"]; }
            set { dRow["BankId"] = value; }
        }

        public string columnBankName
        {
            get
            {
                return BankField.GetBankField.Find(bf =>
                    { return bf.Id == (int)dRow["BankId"]; }).Name;
            }
        }

        public DateTime columnStartDate
        {
            get { return (DateTime)dRow["StartDate"]; }
            set { dRow["StartDate"] = value; }
        }

        public string columnName
        {
            get { return (string)dRow["Name"]; }
            set { dRow["Name"] = value; }
        }

        public decimal columnMoney
        {
            get { return (decimal)dRow["Money"]; }
            set { dRow["Money"] = value; }
        }
        /// <summary>
        /// 账单日
        /// </summary>
        public int columnDay
        {
            get { return (int)dRow["Day"]; }
            set { dRow["Day"] = value; }
        }
        /// <summary>
        /// 期数
        /// </summary>
        public int columnTime
        {
            get { return (int)dRow["Time"]; }
            set { dRow["Time"] = value; }
        }

        public int InterestId
        {
            get { return (int)dRow["InterestId"]; }
            set { dRow["InterestId"] = value; }
        }

        public string columnInterestName
        {
            get { return (string)KMData.DataTableInterest.Select("Id = " + InterestId)[0]["Name"]; }
        }

        public bool columnUseCredit
        {
            get { return (bool)dRow["UseCredit"]; }
            set { dRow["UseCredit"] = value; }
        }

        public bool columnCompound
        {
            get { return (bool)dRow["Compound"]; }
            set { dRow["Compound"] = value; }
        }
    }
    #endregion

    #region BankField
    public class BankField
    {
        public decimal AvailableCredit()
        {
            decimal de = 0;
            foreach (RegularEntryField rf in RegularEntryField.GetRegularEntryField.FindAll(gref =>
            { return gref.BankId == this.Id && gref.Finish != gref.columnTime; }))
            {
                de += (rf.columnTime - rf.Finish) * rf.MoneyPerTime;
            }
            return (Credit + ((Balance>0)?0:Balance )+ de);
        }

        public void SetBankBalance(decimal money)
        {
            Balance = Balance + money;
        }

        public static bool VerifyWhetherSufficientToPay(int bankId,decimal expenses)
        {
            Debug.Assert(fields.Count != 0);

            BankField bf = fields.Find(f => { return f.Id == bankId; });
            return (bf.Credit + bf.Balance - Math.Abs(expenses)) > 0;
        }


        static List<BankField> fields = new List<BankField>();
        public static List<BankField> GetBankField
        {
            get
            {
                if (fields.Count == 0)
                {
                    foreach (DataRow row in KMData.DataTableBanks.Rows)
                        fields.Add(new BankField(row));

                    Debug.Assert(fields.Count != 0, "BankField");
                }
                return fields;
            }
        }

        public void Remove()
        {
            //移除相应的账务记录
            foreach (EntryField f in EntryField.GetEntryField.FindAll(ef => { return ef.BankId == Id; }))
            {
                KMData.DataTableEntrys.Rows.Remove(f.Row);
                EntryField.GetEntryField.Remove(f);
            }

            KMData.DataTableBanks.Rows.Remove(dRow);
            fields.Remove(this);
        }

        bool add = false;
        public void AddNewRowToDataTable()
        {
            if (!add)
                return;

            KMData.DataTableBanks.Rows.Add(dRow);
            fields.Add(this);
            add = false;
        }

        DataRow dRow = null;
        public BankField(DataRow row)
        {
            if (row == null)
            {
                dRow = KMData.DataTableBanks.NewRow();
                Name = LanguageUtil.新钱袋;
                add = true;
            }
            else
            dRow = row;
        }

        public string Url
        {
            get { return (string)dRow["Url"]; }
        }

        public decimal Balance
        {
            get { return (decimal)dRow["Balance"]; }
            set { dRow["Balance"] = value; }
        }

        public decimal Credit
        {
            get { return (decimal)dRow["Credit"]; }
        }

        public int Id
        {
            get { return (int)dRow["Id"]; }
        }

        public string Name
        {
            get
            {
                return (string)dRow["Name"];
            }
            set { dRow["Name"] = value; }
        }

        public bool Default
        {
            get { return (bool)dRow["Default"]; }
            set { dRow["Default"] = value; }
        }

        /// <summary>
        /// 钱袋是否可见
        /// </summary>
        public bool Visible
        {
            get { return (bool)dRow["Visible"]; }
            set
            {
                dRow["Visible"] = value;
            }
        }

        /// <summary>
        /// 钱袋是否启用
        /// </summary>
        public bool Enable
        {
            get { return (bool)dRow["Enable"]; }
            set { dRow["Enable"] = value; }
        }
    }
    #endregion

    #region GroupField
    public class GroupField
    {
        public void Remove(bool removeEntryField)
        {
            foreach (GroupField group in fields.FindAll(gf => { return gf.ParentGroupId==Id; }))
                group.Remove(removeEntryField);

            if (removeEntryField)
                foreach (EntryField f in EntryField.GetEntryField.FindAll(ef => { return ef.GroupId == Id; }))
                    f.Remove();

            KMData.DataTableGroups.Rows.Remove(dRow);
            fields.Remove(this);
        }

        static List<GroupField> fields = new List<GroupField>();
        public static List<GroupField> GetGroupField
        {
            get
            {
                if (fields.Count == 0)
                {
                    foreach (DataRow row in KMData.DataTableGroups.Rows)
                        fields.Add(new GroupField(row));

                    Debug.Assert(fields.Count != 0, "GroupField");
                }
                return fields;
            }
        }

        public static bool GetGroupType(int groupId)
        {
            Debug.Assert(fields.Count != 0);

            return fields.Find(f => { return f.Id == groupId; }).IorE;
        }

        public static List<int> GetAllSubGroupIds(int parentGroupId)
        {
            List<int> ids = new List<int>();
            foreach (DataRow row in KMData.GetAllSubGroupRows(parentGroupId))
                ids.Add((int)row["Id"]);

            return ids;
        }

        public static string[] GetGroupNames(List<GroupField> fields)
        {
            List<string> comboxItems = new List<string>();
            foreach (GroupField gf in fields)
            {
                if (gf.ParentGroupId == 0)
                {
                    gf.index = comboxItems.Count;
                    comboxItems.Add(gf.Name);
                    if (fields.Find(f=> { return f.ParentGroupId == gf.Id; }) != null)
                        ReFillGroups(1, gf.Id, fields, comboxItems);
                }
            }
            return comboxItems.ToArray();
        }

        private static void ReFillGroups(int level, int Id, List<GroupField> fields, List<string> comboxItems)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < level; i++)
                sb.Append("..");

            foreach (GroupField gf in fields.FindAll(delegate(GroupField gfield) { return gfield.ParentGroupId == Id; }))
            {
                gf.index = comboxItems.Count;
                comboxItems.Add(sb.ToString() + gf.Name);
                if (fields.Find(delegate(GroupField gfield) { return gfield.ParentGroupId == gf.Id; }) != null)
                    ReFillGroups(level + 1, gf.Id, fields, comboxItems);

            }
            sb.Remove(0, sb.Length);
        }

        public static GroupField GetDefaultGroup(bool income)
        {
            DataRow o = KMData.DataTableGroups.Select("Id <> -1 and ParentGroupId = 0 and IorE = " + income.ToString())[0];
            if (o == null)
                o = KMData.DataTableGroups.Select("Id <> -1 and IorE = " + income.ToString())[0];

            if (o == null)
            {
                Debug.Assert(false,income ? LanguageUtil.缺乏收入群组 : LanguageUtil.缺乏支出群组);
                return null;
            }
            else
                return new GroupField(o);
        }
        /// <summary>
        /// 移除群组并清除其所属的账务记录和子群组
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        //public static bool RemoveGroupField(GroupField field)
        //{
        //    foreach (EntryField ef in EntryField.GetEntryField.FindAll(f => { return f.GroupId == field.Id; }))
        //        EntryField.RemoveEntryField(ef);

        //    foreach (GroupField gf in GroupField.GetGroupField.FindAll(f => { return f.ParentGroupId == field.Id; }))
        //        RemoveGroupField(gf);

        //    KMData.DataTableGroups.Rows.Remove(field.dRow);
        //    GroupField.GetGroupField.Remove(field);
        //    return true;
        //}

        DataRow dRow = null;
        public GroupField(DataRow row)
        {
            dRow = row;
        }

        bool add = false;
        public void AddNewRowToDataTable()
        {
            if (!add)
                return;

            KMData.DataTableGroups.Rows.Add(dRow);
            fields.Add(this);
            add = false;
        }

        public GroupField(int parentGroupId, string text,bool income)
        {
            dRow = KMData.DataTableGroups.NewRow();
            dRow["ParentGroupId"] = parentGroupId;
            dRow["Name"] = text;
            dRow["IorE"] = income;
            add = true;
        }

        int index = 0;//由于没有做排序,导致Combox中索引值无法对应Id值,所以做此属性
        public int Index
        {
            get { return index; }
        }

        public string Note
        {
            get { return (string)dRow["Note"]; }
            set { dRow["Note"] = value; }
        }

        public int Id
        {
            get { return (int)dRow["Id"]; }
        }

        public int ParentGroupId
        {
            get { return (int)dRow["ParentGroupId"]; }
            set { dRow["ParentGroupId"] = value; }
        }

        public string Name
        {
            get { return (string)dRow["Name"]; }
            set { dRow["Name"] = value; }
        }

        public bool IorE
        {
            get { return (bool)dRow["IorE"]; }
            set { dRow["IorE"] = value; }
        }

        public int IconIndex
        {
            get { return (int)dRow["IconIndex"]; }
            set { dRow["IconIndex"] = value; }
        }
    }
    #endregion

    #region ExchangeField
    class ExchangeField
    {
        static List<ExchangeField> fields = new List<ExchangeField>();
        public static List<ExchangeField> GetExchangeField
        {
            get
            {
                if (fields.Count == 0)
                    ExchangeUtil.DownloadExchange(fields);

                return fields;
            }
        }

        public static void Init()
        {
            ExchangeUtil.DownloadExchange(fields);
        }

        public ExchangeField(string name, string flag, string rate)
        {
            this.name = name;
            this.flag = flag;
            this.rate = rate;
        }

        string name = string.Empty;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        string flag = string.Empty;
        public string Flag
        {
            get { return flag; }
            set { flag = value; }
        }

        string rate = "1";
        public string Rate
        {
            get { return rate; }
            set { rate = value; }
        }
    }
#endregion
}
